package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import lombok.NoArgsConstructor;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import sun.java2d.pipe.AlphaPaintPipe;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-20
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {
    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //如果账号密码为空，返回不存在
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //不为空👇
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(queryWrapper);
        //通过账号 查询数据库的对象返回 看看对象是否存在 不存在继续抛异常
        if (StringUtils.isEmpty(one)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //存在的话 获取数据这个对象的密码
        String password = one.getPassword();
        String password1 = dto.getPassword();
        //通过输入的密码 123456 获取到查询出来的对象的salt
        String salt = one.getSalt();
        //拼接 通过MD5加密
        String sum = password1 + salt;
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(sum.getBytes());
        //判断前后端密码是否相同
        if (! md5DigestAsHex.equals(password)){
            //不相同抛异常
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //相同就去创建token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",one.getId());
        String token = AppJwtUtil.getToken(map);
        //存放用户ID 👈 token中
        //ResponseResult.ok(Map)   Map = "user",获取数据这个对象的密码 Map = "token",/相通就去创建token
        HashMap<Object, Object> response = new HashMap<>();
        one.setPassword(null);
        one.setSalt(null);
        response.put("user",one);
        response.put("token",token);
        //ResponseResult.ok(👆map)
        return ResponseResult.okResult(response);
    }
}
